package com.course.cases;

import com.alibaba.fastjson.JSONArray;
import com.course.config.TestConfig;
import com.course.model.GetUserInfo;
import com.course.model.User;
import com.course.utils.DatabaseUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.session.SqlSession;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author bigFish
 * @Title: public:
 */
public class GetUserInfoTest {


    @Test(dependsOnGroups = "loginTrue", description = "查询用户信息")
    public void getInfo() throws IOException{
        SqlSession sqlSession = DatabaseUtil.getSqlSession();

        //1.获取用例
        GetUserInfo userInfoCase = sqlSession.selectOne("getUserInfoCase", 1);
        System.out.println("请求地址："+TestConfig.getUserInfoUrl);
        System.out.println("用例："+userInfoCase);

        //2.发起请求获取响应结果
        String result = getResult(userInfoCase);

        //3.本地查询数据结果
        User result1 = sqlSession.selectOne(userInfoCase.getExpected(), userInfoCase);
        System.out.println("本地查询结果为："+result1);
        //需要先转换为ArrayList,才能转换为JSONArray
        List arrayList = new ArrayList();
        arrayList.add(result1);
        JSONArray jsonArray = new JSONArray(arrayList);

        System.out.println("本地查询转换结果："+result1);
        System.out.println("网络请求结果："+result.replaceAll("\"", ""));

        //4.判断结果
        Assert.assertEquals(result.replaceAll("\"", ""),result1.toString());

    }

    private String getResult(GetUserInfo userInfoCase) throws IOException {
        //设置请求类型
        HttpPost httPost = new HttpPost(TestConfig.getUserInfoUrl);
        //设置参数
//        JSONObject param = new JSONObject();
//        param.put("id",userInfoCase.getUserId());
        String param = String.valueOf(userInfoCase.getUserId());
        //设置请求头
        httPost.setHeader("Content-Type", "application/json");
        //添加请求携带的参数
        StringEntity entity = new StringEntity(param, "utf-8");
        httPost.setEntity(entity);
        //发起请求
        CloseableHttpResponse response = TestConfig.getHttpClient().execute(httPost);
        //获取结果实体
        String string = EntityUtils.toString(response.getEntity());
        //转换数据格式
        //数组转换ArrayList集合
//        ArrayList arrayList = new ArrayList(Collections.singleton(string));
//        List result = Arrays.asList(string);
        //转换为JSONArray集合
//        JSONArray jsonArray = new JSONArray(arrayList);

        System.out.println("请求结果:"+string);
//        System.out.println("Arrays类的静态内部类:"+result);
//        System.out.println("JSONArray类:"+jsonArray);
        return string;
    }


}
